#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "StdTcp.h"
#include "StdThread.h"
#include "DoubleLinkList.h"

struct Clinet 
{
    char name[20];
    int sock;
};
typedef struct Clinet  C;
C *Create(const char *name,int sock)
{
    C *c=(C *)malloc(sizeof(C));
    if(c==NULL)
    {
        perror("malloc");
        return NULL;
    }
    strcpy(c->name,name);
    c->sock=sock;
    return c;
}
void FreeC(C *c)
{
    free(c);
}
DLList ClinetList;
struct Message
{
    int flag;
    char fromname[20];
    char toname[20];
    char content[1024];
};
typedef struct Message Msg;
void *thread_headle(void *arg)
{
    int sock=*((int*)arg);
    while(1)
    {
        Msg m;
        TcpServerRecv(sock,&m,sizeof(m));
        switch (m.flag)
        {
        case 1:
            // printf("%s\n",m.content);
            InsertTail(&ClinetList,Create(m.fromname,sock));
            break;
        case 2:
            struct Node *TravelPoint=ClinetList.head;
            while(TravelPoint!=NULL)
            {
                C *c=(C*)TravelPoint->data;
                if(strcmp(c->name,m.toname)==0)
                {
                    TcpServerSend(c->sock,&m,sizeof(m));
                    break;
                }
                TravelPoint=TravelPoint->next;
            }
            break;
        default:
            break;
        }
    }
}

void main(int argc,char *argv[])
{
    if(argc!=3)
    {
        printf("invalid numbers");
        return;
    }
    InitDLinkList(&ClinetList);
    TcpS *s=InitTcpServer(argv[1],atoi(argv[2]));
    int acceptsock;
    while((acceptsock=TcpServerAccept(s))>0)
    {
        
        thread *t=InitThread(thread_headle,&acceptsock);
        DetachThread(t);
        // char temp[100]={0};
        // TcpServerRecv(acceptsock,temp,100);
        // printf("Recv:%s\n",temp);
    }
}